package com.sinosun.autotestmachine.tools.reader;

import java.util.ArrayList;
import java.util.List;

import org.xutils.x;
import org.xutils.common.Callback;
import org.xutils.ex.HttpException;
import org.xutils.http.RequestParams;

import com.sinosun.autotestmachine.App;
import com.sinosun.autotestmachine.tools.TaskManager;
import com.sinosun.autotestmachine.tools.parser.CaseInformation;
import com.sinosun.autotestmachine.tools.parser.FileContentParser;
import com.sinosun.autotestmachine.tools.parser.NetInformationParser;
import com.sinosun.autotestmachine.tools.parser.ParamKey;
import com.sinosun.autotestmachine.tools.proxy.ErrorCode;
import com.sinosun.mstplib.remote.mstplib.util.DeviceId;

import android.text.TextUtils;
import android.util.Log;

public class NetCaseMaker {
	private static String platForm = "Android";
	private static String port = String.valueOf(App.getTestConfig().getAutoTestServerPort());
	private static String ip = App.getTestConfig().getAutoTestServerHost();
	
	public static void getTask() {
		
		Log.e("XXX", "NetCaseMaker getTask port> " + port + ", ip>" + ip);
		Callback.CommonCallback<String> callback = new Callback.CommonCallback<String>() {
			@Override public void onSuccess(String result) {
				Log.e("XXX", "[getTask] get result:" + result);
				NetInformationParser nfp = new NetInformationParser(result);
				if (nfp.getCode() == ErrorCode.SUCCESS) {
					if (nfp.getType() == 0) {			//收到测试用例
						List<String> allCase = nfp.getContent();
						int i = 0;
						Log.e("XXX", "size -> allCase = " + allCase.size());
						for (String testCase : allCase) {
							Log.e("XXX", "i -> testCase = " + testCase);
							i++;
							if (i >= allCase.size()) {
								CaseInformation caseInformation = FileContentParser.parser(testCase, true, nfp.getTaskId());
								if (caseInformation != null) {
									TaskManager.getTaskManager().putTask(caseInformation);		//向任务队列中添加新的数据
								}
							} else {
								CaseInformation caseInformation = FileContentParser.parser(testCase, nfp.getTaskId());
								if (caseInformation != null) {
									TaskManager.getTaskManager().putTask(caseInformation);		//向任务队列中添加新的数据
								}
							}
						}
						
						//累计用例总数，添加完所有用例以后，开启测试线程
						TaskManager.getTaskManager().realStartTest();
						Log.e("XXX", "TaskManager.getTaskManager().getLoopNumber() " + TaskManager.getTaskManager().getLoopNumber());
						Log.e("XXX", "allCase.size() " + allCase.size());
						TaskManager.getTaskManager().setLoopNumber(TaskManager.getTaskManager().getLoopNumber() + allCase.size());
						NetCaseMaker.reportDeviceStatus(Status.BUSY);
					} else if (nfp.getType() == 1) {
						Log.e("XXX", "get stop order: task->" + nfp.getTask());
						Log.e("XXX", "get stop order: taskID->" + nfp.getTaskId());
						App.runInformation.setRunFlag(false);
						if (TextUtils.isEmpty(nfp.getTask())) {
							App.runInformation.setTasks(new ArrayList<String>());
						} else {
							App.runInformation.addTask(nfp.getTask());
						}
						App.runInformation.setCodeByNet(true);
						App.runInformation.setTaskId(nfp.getTaskId());
					} else {
						
					}
				}
			}
			
			@Override public void onError(Throwable ex, boolean isOnCallback) {
				if (ex instanceof HttpException) { // 网络错误
					HttpException httpEx = (HttpException) ex;
					int responseCode = httpEx.getCode();
					String responseMsg = httpEx.getMessage();
					String errorResult = httpEx.getResult();
				} else { // 其他错误
				}
			}
			
			@Override public void onCancelled(CancelledException cex) {
			}

			@Override public void onFinished() {
				getTask();
			}
		};
		
		RequestParams params = new RequestParams();
		params.addParameter(ParamKey.PLAT_FORM, platForm);
		params.addParameter(ParamKey.DEVICE_ID, DeviceId.getDeviceId());
		params.setUri("http://" + ip + ":" + port + "/autotest/testPlatform/persistentConnection");
		params.setConnectTimeout(60*1000*10);
		params.setReadTimeout(60*1000*10);
		x.http().post(params, callback);
	}
	
	public static void reportTaskResult(final String taskID, final String type, final String content, final String code) {
		Log.e("XXX", "NetCaseMaker reportTaskResult");
		Callback.CommonCallback<String> a = new Callback.CommonCallback<String>() {
			@Override public void onSuccess(String result) {
				Log.e("XXX", "[reportTaskResult] get result:" + result);
			}
			
			@Override public void onError(Throwable ex, boolean isOnCallback) {
				if (ex instanceof HttpException) { // 网络错误
					HttpException httpEx = (HttpException) ex;
					int responseCode = httpEx.getCode();
					String responseMsg = httpEx.getMessage();
					String errorResult = httpEx.getResult();
					Log.e("XXX", "responseCode:" + responseCode);
					Log.e("XXX", "responseMsg:" + responseMsg);
					Log.e("XXX", "errorResult:" + errorResult);
				} else { // 其他错误
				}
				Log.e("XXX", "[reportTaskResult] error:" + ex.getMessage());
				reportTaskResult(taskID, type, content, code);
			}
			
			@Override public void onCancelled(CancelledException cex) {
				Log.e("XXX", "[reportTaskResult] canceled");
			}

			@Override public void onFinished() { }
		};
		
		RequestParams params = new RequestParams();
		params.addParameter(ParamKey.PLAT_FORM, platForm);
		params.addParameter(ParamKey.DEVICE_ID, DeviceId.getDeviceId());
		params.addParameter(ParamKey.TASK_ID, taskID);
		params.addParameter(ParamKey.TYPE, type);
		params.addParameter(ParamKey.CONTENT, content);
		params.addParameter(ParamKey.CODE, code);
		params.setUri("http://" + ip + ":" + port + "/autotest/report");
		x.http().post(params, a);
	}
	
	public static void reportDeviceStatus(final Status state) {
		Log.e("XXX", "NetCaseMaker reportDeviceStatus " + state.valueStr());
		Callback.CommonCallback<String> a = new Callback.CommonCallback<String>() {
			@Override public void onSuccess(String result) {
				Log.e("XXX", "[reportDeviceStatus] get result:" + result);
			}
			
			@Override public void onError(Throwable ex, boolean isOnCallback) {
				if (ex instanceof HttpException) { // 网络错误
					HttpException httpEx = (HttpException) ex;
					int responseCode = httpEx.getCode();
					String responseMsg = httpEx.getMessage();
					String errorResult = httpEx.getResult();
					Log.e("XXX", "responseCode:" + responseCode);
					Log.e("XXX", "responseMsg:" + responseMsg);
					Log.e("XXX", "errorResult:" + errorResult);
				}
				Log.e("XXX", "[reportDeviceStatus] error:" + ex.getMessage());
				reportDeviceStatus(state);
			}
			
			@Override public void onCancelled(CancelledException cex) {
				Log.e("XXX", "[reportDeviceStatus] canceled");
			}

			@Override public void onFinished() { }
		};
		
		RequestParams params = new RequestParams();
		params.addParameter(ParamKey.PLAT_FORM, platForm);
		params.addParameter(ParamKey.DEVICE_ID, DeviceId.getDeviceId());
		params.addParameter(ParamKey.STATUS, state.valueStr());
		params.setUri("http://" + ip + ":" + port + "/autotest/testPlatform/state");
		x.http().post(params, a);
	}
}
